<?php

/**
 * Statyczna klasa zawierająca różne narzędzia
 *
 * @author Lukas
 */
class Application {

    public static $banned = array("select", "update", "delete", "alter");

    /**
     * Metoda do sprawdzania zawartości zmiennych tablicowych
     *
     * @param array() $tab tablica do przeanalizowania
     */
    static public function debugArray($tab) {
        echo "<pre>";
        print_r($tab);
        echo "</pre>";
    }

    static public function getCountrySelect($selected=0, $name = 'country') {

        require_once 'pgb/Country.php';
        $html = new Html();
        $sources = Country::getAll();
        $optO = ( $selected != 0 ? array(array("value", "0")) : array(array("value", "0"), array("SELECTED")) );
        $options = $html->tagElementSimple("option", "", "", $optO, "---");

        foreach ($sources as $source) {
            $optO = '';
            if ($selected != $source['id']) {
                $optO = array(array("value", $source['id']));
            } else {
                $optO = ( $selected != $source['id'] ? array(array("value", $source['id'])) : array(array("value", $source['id']), array("SELECTED")) );
            }
            $options .= $html->tagElementSimple("option", "", "", $optO, $source['country']);
        }

        $select = $html->tagElementSimple("select", $name, "", array(), $options);
        return $select;
    }

    static public function getSitePath() {
        return APPLICATION_PATH . '/';
    }

    public static function chandeCandidateCvPath() {
        $sql = "select id,cand_firstname,cand_lastname from bazcan_candidate";
        $results = DBManager::getArrayData($sql);
        $doc_dir = "DOKUMENTY/KANDYDACI/";
        if (mysql_error())
            echo mysql_error();
        echo count($results);
        foreach ($results as $result) {
            $old_dir = $doc_dir . self::polNaEngZnaki($result['cand_firstname']) . "_" . self::polNaEngZnaki($result['cand_lastname']);
            $new_dir = $doc_dir . self::polNaEngZnaki($result['cand_firstname']) . "_" . self::polNaEngZnaki($result['cand_lastname']) . "_" . $result['id'];
            if (!is_dir($new_dir) && is_dir($old_dir))
                echo $result['id'] . "...changing..." . rename($old_dir, $new_dir);
            else if (is_dir($new_dir))
                echo $result['id'] . " - PRESENT";
            else
                echo 'brak';
        }
    }

    /**
     * 
     * Funkcja rejestrująca i logująca do pliku nazwiska i imiona kandydatów 
     * dla których są wpisuy o plikach w bazie a nie ma ich fizycznie we wpisanej lokalizacji
     * @param int $daysBack - ilość dni wstecz
     */
    public static function logCandidatesWithMissingFiles($daysBack, $delete=false) {
        $doc_dir = "DOKUMENTY/KANDYDACI/";
        $date = date("Y-m-j");
        $logChangeDate = @date("Y-m-j", filectime('_files/log/cand_missing_files_log.log'));
        if ($date != $logChangeDate) {
            $newdate = strtotime("-" . $daysBack . " day", strtotime($date));
            $newdate = date('Y-m-j', $newdate);
            $sql = "SELECT c.id,c.cand_firstname,c.cand_lastname,CONCAT(d.doc_path,'/',d.doc_name) as fullpath,d.id as d_id FROM bazcan_candidate c 
					JOIN bazcan_document d ON c.id = d.cand_id WHERE d.doc_add_date >'" . $newdate . "' ORDER BY c.id";
            try {
                $results = DBManager::getArrayData($sql, array());
                $fp = fopen('_files/log/cand_missing_files_log.log', 'a');

                $datetime = new DateTime();

                fwrite($fp, $datetime->format("Y-m-j H-i-s") . " - Searching with date: " . $newdate . "\n");
                @fwrite($fp, "Found " . count($results) . "... Processing...\n");
                foreach ($results as $key => $result) {
                    if (!file_exists($result['fullpath']))
                        if (is_resource($fp)) {
                            fwrite($fp, "NO FILE!! - " . $result['id'] . " " . $result['cand_firstname'] . " " . $result['cand_lastname'] . "\n");
                            $old_fullPath = str_replace("_" . $result['id'] . "/", "/", $result['fullpath']);
                            if (file_exists($old_fullPath)) {
                                fwrite($fp, $result['id'] . " Found data ind old path" . "\n");
                                $paths = explode("/", $result['fullpath']);
                                $tmpPath = "";
                                foreach ($paths as $path) {
                                    if ($tmpPath != "")
                                        $tmpPath .= "/";
                                    $tmpPath .= $path;
                                    if (!is_dir($tmpPath) && !is_file($tmpPath))
                                        @mkdir($tmpPath);
                                }
                                if (is_dir(old_fullPath)) {
                                    fwrite($fp, $result['id'] . " Data is a directory...");
                                    if ($delete) {
                                        rmdir(old_fullPath);
                                        fwrite($fp, " Deleted...");
                                    }
                                    fwrite($fp, "\n");
                                } else {
                                    copy($old_fullPath, $result['fullpath']);
                                    fwrite($fp, $result['id'] . " Copied" . "\n");
                                }
                            }
                            if ($delete) {
                                $sql = "DELETE FROM bazcan_document WHERE id=" . $result['d_id'];
                                DBManager::executeUpdateInsert($sql);
                            }
                        }
                }
                fclose($fp);
            } catch (Exception $e) {
                Log::logError($e);
            }
        }
    }

    static public function getErrorDiv($message) {
        $div = "<div id='errorMessageDiv' class='errorMessageDiv'>" . "\n";
        $div .= "<p id='errorMessageSpanTitle' class='errorMessageSpanTitle'>Wystąpił błąd!</p>" . "\n";
        $div .= "<p id='errorMessageSpanContent' class='errorMessageSpanContent'>";
        $div .= $message;
        $div .= "</p></div>";
        return $div;
    }

    static public function hasClientRealization($id) {
        
    }

    static public function getSimpleErrorDiv($message) {
        $div = "<div id='simpleErrorMessageDiv' class='simpleErrorMessageDiv'>" . "\n";
        $div .= "<p id='simpleErrorMessageSpanContent' class='simpleErrorMessageSpanContent'>";
        $div .= $message;
        $div .= "</p></div>";
        return $div;
    }

    static public function getDefaultPortioningHeader($startPage, $iloscStron, $iloscWynikow, $ilWynikow, $baseURL = '') {
        $naglowekStronicDiv = "<div>" . "\n";
        if ($iloscWynikow > $ilWynikow) {
            if ($startPage < 6) {
                $left = 1;
                $right += 5 - $startPage;
            } else
                $left = $startPage - 4;

            if ($startPage > $iloscStron - 5) {
                $right += $iloscStron;
                $left -= 5 - ($iloscStron - $startPage);
            } else
                $right += $startPage + 5;

            if ($left < 1)
                $left = 1;
            if ($right > $iloscStron)
                $right = $iloscStron;


            if ($left > 1) {
                $naglowekStronicDiv .= "<a href='" . $baseURL . "&page=1'>Pierwsza</a> " . "\n";
                $naglowekStronicDiv .= "| " . "\n";
            }
            if ($left > 7) {
                $naglowekStronicDiv .= "<a href='" . $baseURL . "&page=" . ( $startPage - 10 ) . "'><< Cofnij o 10</a>" . "\n | ";
            }

            for ($p = $left; $p <= $right; $p++) {
                if ($p != $startPage) {
                    $naglowekStronicDiv .= "<a href='" . $baseURL . "&page=" . $p . "'>" . $p;
                    if ($p != $right)
                        $naglowekStronicDiv .= ",&nbsp;";
                    $naglowekStronicDiv .="</a>";
                } else {
                    $naglowekStronicDiv .= "<b><u>" . $p . "</u></b>,&nbsp;";
                }
            }

            $naglowekStronicDiv .= " (wyników - ".$iloscWynikow.") ";            
            
            if ($right + 5 < $iloscStron) {
                $naglowekStronicDiv .= " | <a href='" . $baseURL . "&page=" . ( $startPage + 10 ) . "'>Przeskocz o 10 >> </a>" . "\n";
            }
            if ($right < $iloscStron) {
                $naglowekStronicDiv .= " | <a href='" . $baseURL . "&page=" . $iloscStron . "'>Ostatnia</a>" . "\n";
            }
        } elseif ($iloscWynikow > 0) {
            $naglowekStronicDiv .= " Strona 1 z 1  " . "\n";
        } else {
            $naglowekStronicDiv .= " Brak wyników " . "\n";
        }

        $naglowekStronicDiv .= "</div>" . "\n";
        return $naglowekStronicDiv;
    }

    /**
     * Metoda stronnicująca wyniki zapytańna stronie
     *
     * @param string    $query          zapytanie które ma podlegać porcjowaniu
     * @param string    $URL główny     link do którego dobudowane będą linki kontrolek
     * @param int       $ilWynikow      ilość wyników pokazywanych na stronie
     * @param int       $liczbaWyn      opcjonalny parametr mówiący ile wyników jest ogółem
     */
    static public function getPortioningData($query, $URL, $ilWynikow, $distCol='*', $liczbaWyn=0) {
        $iloscWynikow = 0;
        $startPage = ( isset($_GET['page']) ? (int) $_GET['page'] : 1 );

        if (!strpos($URL, "&page")) {
            $baseURL = $URL;
        } else {
            $baseURL = substr($URL, strpos($URL, "&page"), strlen($URL) - (strpos($URL, "&page")));
            $baseURL = str_replace($baseURL, "", $URL);
        }

        $PRM = array();

        if (is_array($query)) {
            $PRM = $query['PRM'];
            $query = $query['query'];
        }

        $countQuery = substr($query, strpos($query, "SELECT") + 6, strpos($query, "FROM") - (strpos($query, "SELECT") + 6));
        $countQuery = str_replace($countQuery, " count(" . $distCol . ") as il ", $query);
        if ($liczbaWyn == 0 && $query) {
            try {
                $wynik = DBManager::getArrayData($countQuery, $PRM);
                $iloscWynikow = $wynik[0][il];
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
        } else {
            $iloscWynikow = $liczbaWyn;
        }
        if ($iloscWynikow > $ilWynikow) {
            $query = $query . " LIMIT " . ( ( $startPage - 1 ) * $ilWynikow ) . "," . $ilWynikow;
            $iloscStron = ceil($iloscWynikow / $ilWynikow);
        }

        $naglowekStronicDiv = self::getDefaultPortioningHeader($startPage, $iloscStron, $iloscWynikow, $ilWynikow, $baseURL);

        return array(
            "query" => $query,
            "naglowekDiv" => $naglowekStronicDiv
        );
    }

    /**
     * Oblicza dla podanych parametrow wartosci do LIMIT w zapytaniu
     * @param int $startPage
     * @param int $wynikow_na_strone
     * @param int $wyniki_razem
     * @return array()
     */
    public static function pageing($startPage, $wynikow_na_strone, $wyniki_razem) {
        if ($wyniki_razem > $wynikow_na_strone) {
            $od = ( ( $startPage - 1 ) * $wynikow_na_strone );
            $iloscStron = ceil($wyniki_razem / $wynikow_na_strone);
        } else {
            $od = 0;
            $iloscStron = 1;
        }

        return array($od, $wynikow_na_strone, $iloscStron);
    }

    //TODO FUNKCJA SKOPIOWANA Z CandidatesViewManager (DROBNA ZMIANA)
    static public function getSourcesSelect($selected=0, $name = 'cand_source') {

        $html = new Html();
        $sources = Candidate_Source::getList2Select();
        $optO = ( $selected != 0 ? array(array("value", "0")) : array(array("value", "0"), array("SELECTED")) );
        $options = $html->tagElementSimple("option", "", "", $optO, "---");
        $headhuntingID =0;

        foreach ($sources as $source) {
            if(stristr($source['source_name'],"head") && stristr($source['source_name'],"hunting")){
              $headhuntingID = $source['id'];
              if($selected==$headhuntingID || $selected===0){
                $optO = ( $selected != $source['id'] ? array(array("value", $source['id'])) : array(array("value", $source['id']), array("SELECTED")) );
                $options .= $html->tagElementSimple("option", "", "", $optO, $source['source_name']);
              }
            }else{
              $optO = ( $selected != $source['id'] ? array(array("value", $source['id'])) : array(array("value", $source['id']), array("SELECTED")) );
              $options .= $html->tagElementSimple("option", "", "", $optO, $source['source_name']);
            }
        }
        $extraOpt = array();
        $select = "";
        if($selected==$headhuntingID){
          $extraOpt[] = array('disabled','disabled');
          $select .= $html->tagElementSimple("input", $name,"", array(array("value",$selected),array("type","hidden")));
          $select .= $html->tagElementSimple("select", "", "", $extraOpt, $options);
        }else{
          $select = $html->tagElementSimple("select", $name, "", $extraOpt, $options);
        }
        
        
        return $select;
    }

    static public function getStatesSelect($selected=0) {
        require_once 'pgb/States.php';

        $html = new Html();
        $opt = ( $selected == 0 ? array(array("value", "0"), array("SELECTED")) : array(array("value", "0")) );
        $options = $html->tagElementSimple("option", "", "", $opt, "---");
        $STATES = States::getList();

        foreach ($STATES as $key => $state) {
            $opt = ( $selected === $state ? array(array("value", $key + 1), array("SELECTED")) : array(array("value", $key + 1)) );
            $options .= $html->tagElementSimple("option", "", "", $opt, $state);
        }
        $select = $html->tagElementSimple("select", "states", "", array(), $options);
        return $select;
    }

    static public function getStatesIdSelect($selected=0) {
        require_once 'pgb/States.php';

        $html = new Html();
        $opt = ( $selected == 0 ? array(array("value", "0"), array("SELECTED")) : array(array("value", "0")) );
        $options = $html->tagElementSimple("option", "", "", $opt, "---");
        $i = 0;
        $STATES = States::getList();

        foreach ($STATES as $state) {
            $i++;
            $opt = ( $selected === $state ? array(array("value", $i), array("SELECTED")) : array(array("value", $i)) );
            $options .= $html->tagElementSimple("option", "", "", $opt, $state);
        }
        $select = $html->tagElementSimple("select", "states", "", array(), $options);
        return $select;
    }

    static public function parsePost($odrzuc = array(), $arr="POST") {
        $post = array();
        $array = $_POST;
        if (!is_array($odrzuc)) {
            $odrzuc = array($odrzuc);
        }
        switch ($arr) {
            case "POST": $array = $_POST;
                break;
            case "GET": $array = $_GET;
                break;
        }
        if (!is_array($array)) {
            return array();
        }
        foreach ($array as $postKey => $postVal) {
            $dopusc = true;
            foreach (self::$banned as $banWord)
                if (!is_array($postVal) && ( ( stripos($postVal, " " . $banWord . " ") !== false ) || (strncmp($banWord . " ", $postVal, strlen($banWord . " ")) == 0) )) {
                    $dopusc = false;
                    Log::logError("Podczas parsowania " . $arr . " odzucono: " . $postVal . " POWOD: " . $banWord);
                }
            if ($postVal != "" && !in_array($postVal, $odrzuc) && $dopusc)
                if (!is_array($postVal))
                    $post[$postKey] = trim($postVal);
                else
                    $post[$postKey] = $postVal;
        }

        //jesli nie byl przekazany site, ustaw wartosc pusta (notice'y)
        if (!(in_array("site", $odrzuc) || isset($post['site']))) {
            $post['site'] = '';
        }

        return $post;
    }

    static public function getModuleCsses() {
        $htmlCssLinks = "";

        if (isset($_GET['action'])) {
            $module = $_GET['action'];

            $cssPath = Module::getModuleObj($module)->getModulePath() . "/css/";
            $catContent = @scandir($cssPath);

            if (!is_array($catContent))
                $catContent = array();
            foreach ($catContent as $element)
                if ($element != "." && $element != "..") {
                    $rozsz = explode(".", $element);
                    $rozsz = $rozsz[count($rozsz) - 1];
                    if ($rozsz == "css") {
                        if (stripos($element, "ext_") !== 0)
                            $htmlCssLinks .= "<link rel=\"stylesheet\" href=\"" . $cssPath . $element . "\" type=\"text/css\" />";
                    }
                }
        }
        return $htmlCssLinks;
    }

    static public function getModuleJses() {
        $htmlJsLinks = "";

        if (isset($_GET['action'])) {
            $module = $_GET['action'];
            $jsPath = Module::getModuleObj($module)->getModulePath() . "/js/";
            $catContent = @scandir($jsPath);
            $htmlJsLinks = "\n";
            if (!is_array($catContent))
                $catContent = array();

            foreach ($catContent as $element)
                if ($element != "." && $element != "..") {
                    $rozsz = explode(".", $element);
                    $rozsz = $rozsz[count($rozsz) - 1];
                    if ($rozsz == "js") {
                        if (stripos($element, "ext_") !== 0)
                            $htmlJsLinks .= "<script src=\"" . $jsPath . $element . "\" type=\"text/javascript\"></script>" . "\n";
                    }
                }
        }
        return $htmlJsLinks;
    }

    static public function getExternalModuleCsses() {
        $htmlCssLinks = "";
        $conf = Config::get('modules');
        $conf = $conf->toArray();
        $extModules = $conf['modules']['external']['modules'];
        $extModules = explode(",", $extModules);

        foreach ($extModules as $extModule) {
            $module = $extModule;

            $cssPath = Module::getModuleObj($module)->getModulePath() . "/css/";
            $catContent = @scandir($cssPath);
            if (!is_array($catContent))
                $catContent = array();
            foreach ($catContent as $element)
                if ($element != "." && $element != ".." && strpos($element, "ext_") === 0) {
                    $rozsz = explode(".", $element);
                    $rozsz = $rozsz[count($rozsz) - 1];
                    if ($rozsz == "css") {
                        $htmlCssLinks .= "<link rel=\"stylesheet\" href=\"" . $cssPath . $element . "\" type=\"text/css\" />";
                    }
                }
        }

        return $htmlCssLinks;
    }

    static public function getExternalModuleJses() {
        $htmlJsLinks = "";
        $conf = Config::get('modules');
        $conf = $conf->toArray();
        $extModules = $conf['modules']['external']['modules'];
        $extModules = explode(",", $extModules);

        foreach ($extModules as $extModule) {
            $module = $extModule;
            $jsPath = Module::getModuleObj($module)->getModulePath() . "/js/";
            $catContent = @scandir($jsPath);
            $htmlJsLinks .= "\n";
            if (!is_array($catContent))
                $catContent = array();
            foreach ($catContent as $element)
                if ($element != "." && $element != ".." && strpos($element, "ext_") === 0) {
                    $rozsz = explode(".", $element);
                    $rozsz = $rozsz[count($rozsz) - 1];
                    if ($rozsz == "js") {
                        $htmlJsLinks .= "<script src=\"" . $jsPath . $element . "\" type=\"text/javascript\"></script>" . "\n";
                    }
                }
        }
        return $htmlJsLinks;
    }

    static public function addExternalModulesHtml() {
        $conf = Config::get('modules');
        $conf = $conf->toArray();
        $extModules = $conf['modules']['external']['modules'];
        $extModules = explode(",", $extModules);
        $content = "";
        foreach ($extModules as $extModule) {

            $module = $extModule;
            $classPath = Module::getModuleObj($module)->getModulePath() . "/classes/";
            $catContent = @scandir($classPath);

            if (!is_array($catContent))
                $catContent = array();
            foreach ($catContent as $element)
                if ($element != "." && $element != ".." && strpos($element, "ext_") === 0) {
                    $className = explode(".", $element);
                    $className = $className[0];
                    $className = substr($className, 4);
                    $classPath = str_replace("Modules/", "", $classPath);
                    require_once $classPath . $element;
                    $obj = new $className();
                    $content .= $obj->getContent();
                }
        }
        return $content;
    }

    /**
     *
     * Metoda służy do kasowania katalogów na różne sposoby.
     *
     * @param array() $sciezki - lista scieżek do plików i katalogów przeznaczonych do kasowania
     * @param array() $prametry - tablica parametrów r - jeżeli kasowanie ma być rekursywne
     * w - jeżeli chcemy pominąć wpisy podane w następnym parametrze
     * @param array() $rozszerzenia - wyszczególnienie które wpisy mają lub nie być wykasowane
     *
     * @throws Exception	- gdy podane zostaną niewłaÂ¶ciwe parametry
     *
     */
    static public function deltree($sciezki, $parametry=array(), $rozszerenia=array()) {

        $rekurencyjnie = 'r';
        $pomin_wybrane = 'w';


        if (!is_array($parametry) || !is_array($rozszerenia) || !is_array($sciezki)) {
            throw new Exception("Parametry muszą być podane w tablicy.");
        }




        foreach ($sciezki as $sciezka) {

            if ($sciezka[strlen($sciezka) - 1] == "*") {

                $sciezka = substr($sciezka, 0, sizeof($sciezka) - 2);
            }

            if ($sciezka != "." && $sciezka != "..") {

                if (is_dir($sciezka)) {

                    $zaw = scandir($sciezka);

                    if (!in_array($rekurencyjnie, $parametry)) {

                        foreach ($zaw as $pozycja) {

                            if ($pozycja != "." && $pozycja != "..") {

                                if (is_dir($sciezka . $pozycja)) {

                                    rmdir($sciezka . $pozycja);
                                } else {

                                    $tmp = explode(".", $pozycja);
                                    $rozsz = $tmp[count($tmp) - 1];

                                    if (empty($parametry) || (in_array($pomin_wybrane, $parametry) && !in_array($rozsz, $rozszerenia)) || (!in_array($pomin_wybrane, $parametry) && in_array($rozsz, $rozszerenia))) {
                                        unlink($sciezka . $pozycja);
                                    }
                                }
                            }
                        }
                    } else {
                        $nowaTab = array();
                        foreach ($zaw as $wartosc) {
                            if ($wartosc != "." && $wartosc != "..") {
                                $nowaTab[] = $sciezka . "/" . $wartosc;
                            }
                        }

                        self::deltree($nowaTab, $parametry, $rozszerenia);
                    }

                    @rmdir($sciezka);
                } else {

                    if (count($rozszerenia) == 0) {

                        @unlink($sciezka);
                    } else {

                        $tmp = explode(".", $sciezka);
                        $rozsz = $tmp[count($tmp) - 1];

                        if ((in_array("w", $parametry) && !in_array($rozsz, $rozszerenia)) || (!in_array("w", $parametry) && in_array($rozsz, $rozszerenia))) {

                            @unlink($sciezka);
                        }
                    }
                }
            }
        }
    }

    static public function polNaEngZnaki($string) {
        $pol = array(' ', ',', 'ę', 'ó', 'ą', 'ś', 'ł', 'ź', 'ż', 'ć', 'ń', 'Ę', 'Ó', 'Ą', 'Ś', 'Ł', 'Ż', 'Ź', 'Ć', 'Ń');
        $eng = array('', '', 'e', 'o', 'a', 's', 'l', 'z', 'z', 'c', 'n', 'E', 'O', 'A', 'S', 'L', 'Z', 'Z', 'C', 'N');
        
        $string = str_replace($pol, $eng, $string);
        //$string = preg_replace('/[^A-Za-z.]/', '', $string);
        return $string;
    }

    static public function getDocumentTypeIDByShortName($shortName) {
        require_once 'pgb/Document/Type.php';
        return Document_Type::getTypeByShortName($shortName);
    }

    static public function getDocumentTypeShortNameByID($id) {
        require_once 'pgb/Document/Type.php';
        return Document_Type::getShortNameById($id);
    }

    static public function getDocumentTypeNameByID($id) {
        require_once 'pgb/Document/Type.php';
        return Document_Type::getNameById($id);
    }

    static public function cutTimeFromDateTime($dateTime) {
        $dateTime = substr($dateTime, 0, strpos($dateTime, " "));
        return $dateTime;
    }
    
    

    static public function getCandidateCraftTree($candId) {
        require_once 'pgb/Candidate/Craft.php';

        $craftInfo = Candidate_Craft::getCandTreeInfoList($candId);

        $newCraftInfo = array();
        $subcraftsParents = array();
        foreach ($craftInfo as $craftTmp) {
            $newCraftInfo[$craftTmp["id"]] = $craftTmp;
            if (!in_array($craftTmp["parent_id"], $subcraftsParents)) {
                $subcraftsParents[] = $craftTmp["parent_id"];
                $craftParentTmp =  Candidate_Craft::get($craftTmp["parent_id"]);

                $newCraftInfo[$craftParentTmp["id"]] = $craftParentTmp;
            }
        }
        return $newCraftInfo;
    }

    static public function redirect($to, $code = false) {
        $location = null;
        $skrypt = '';
        $sn = $_SERVER['SCRIPT_NAME'];
        $cp = dirname($sn);

        if (substr($to, 0, 4) == 'http') {
            $location = $to; // Absolute URL
        } else {
            $schema = $_SERVER['SERVER_PORT'] == '443' ? 'https' : 'http';

            //pobierz host na bazie referer
            if (isset($_SERVER['HTTP_REFERER'])) {
                $host = $_SERVER['HTTP_REFERER'];
                $location = str_replace(basename($host), '', $host);
                $location .= $to;
                $host = false;
            } else {
                $host = strlen($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
                $host .= $cp; //Dodane dla zgodności z IE jeśli będzie powodować błędy wywalić, ale nie zapomnieć, że w IE niewłaściwie wyznaczane są ścieszki względne.
            }

            //jesli nie pobrano location z referera to sprubuj na bazie hosta
            if ($host) {

                if (substr($to, 0, 1) == '/') {
                    $location = "$schema://$host$to";
                } elseif (substr($to, 0, 1) == '.') { // Relative Path
                    $location = "$schema://$host/";
                    $pu = parse_url($to);
                    $cd = dirname($_SERVER['SCRIPT_FILENAME']) . '/';
                    $np = realpath($cd . $pu['path']);
                    $np = str_replace($_SERVER['DOCUMENT_ROOT'], '', $np);
                    $location.= $np;

                    if ((isset($pu['query'])) && (strlen($pu['query']) > 0)) {
                        $location.= '?' . $pu['query'];
                    }
                } else {
                    $location = "$schema://$host/$to";
                }
            }
        }

        $hs = headers_sent();

        if ($hs == false) {
            if ($code == 301)
                header("HTTP/1.1 301 Moved Permanently"); // Convert to GET
            elseif ($code == 302)
                header("HTTP/1.1 302 Found"); // Conform re-POST
            elseif ($code == 303)
                header("HTTP/1.1 303 See Other"); // dont cache, always use GET
            elseif ($code == 304)
                header("HTTP/1.1 304 Not Modified"); // use cache
            elseif ($code == 305)
                header("HTTP/1.1 305 Use Proxy");
            elseif ($code == 306)
                header("HTTP/1.1 306 Not Used");
            elseif ($code == 307)
                header("HTTP/1.1 307 Temporary Redirect");
//        else trigger_error("Unhandled redirect() HTTP Code: $code",E_USER_ERROR);

            Log::logInfo(sprintf('redirect to: %s', $location));

            header("Location: $location");
            header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
        }
        elseif (($hs == true) || ($code == 302) || ($code == 303)) {
            $skrypt .="<script type=\"text/javascript\">";
            $skrypt .="window.location.href=\"" . $to . "\";";
            $skrypt .="</script>";
            echo $skrypt;
        }
        exit(0);
    }

    static public function linkMenuButton($menuName, $tagName, $link) {
        $html = new Html();
        $hr = $html->tagElementSimple("hr", "hr" + $tagName, "menuLink", array());

        $spanName = $html->tagElementSimple("span", "span" + $tagName, "menuLink", array(), $menuName);

        $div = $html->tagElementSimple("div", "div" + $tagName, "menuLink", array(
            array("onMouseOver", "javascript:style.backgroundColor='#bbdddd'"),
            array("onMouseOut", "javascript:style.backgroundColor='#bbbbdd'")
                ), $spanName . $hr
        );
        $a = $html->tagElementSimple("a", "a" + $tagName, "menuLink", array(array("href", $link)), $div);

        return $a;
    }

    static public function prepareLogMessage($message, $action, $module="none") {
        return "User: [" . User_Session::getUserName() . "] --- Module:[" . $module . "] --- Action: " . $action . " --- Msg: [" . $message . "]";
    }

    static $images = null;

    static public function getImageName($name) {
        if (self::$images === null) {
            $path = opendir("images");
            if ($path === false) {
                return false;
            }
            while (false !== ($file = readdir($path))) {
                $nazwa = explode(".", $file);
                if (!is_dir("images/" . $file) && trim($nazwa[0])) {
                    unset($nazwa[count($nazwa) - 1]);
                    self::$images[implode(".", $nazwa)] = "images/" . $file;
                    self::$images[$file] = "images/" . $file;
                }
            }
        }
        if (array_key_exists($name, self::$images)) {
            $name = self::$images[$name];
        }
        return $name;
    }

    static public function getImage($image, $imgAttr=array()) {
        if (is_string($imgAttr)) {
            $imgAttr = array("title" => $imgAttr);
        }
        $imgAttr['src'] = self::getImageName($image);
        $html = new Html();

        return $html->simpleTag("img", null, $imgAttr);
    }

    static public function getEditImage($title = 'Edytuj') {
        return self::getImage("edytuj", $title);
        //return "<img src='images/edytuj.png' title='".$title."' />";
    }

    static public function getDeleteImage($title = 'Usuń') {
        return self::getImage("usun", $title);
        //return "<img src='images/usun.png' title='".$title."' />";
    }

    static public function getAddImage($title = 'Dodaj') {
        return self::getImage("dodaj", $title);
        //return "<img src='images/dodaj.png' title='".$title."' />";
    }

    static public function getLoadImage($title = 'Wczytuje') {
        return self::getImage("loading", $title);
        //return "<img src='images/loading.gif' title='".$title."' />";
    }

    static public function getButton($image, $imageTitle, $Attr=array(), $imgAttr=array()) {
        $html = new Html();
        if (empty($Attr['href'])) {
            $Attr['href'] = "javascript:void(0);";
        }
        return $html->simpleTag("a", self::getImage($image, $imageTitle, $imgAttr), $Attr);
    }

    static $html;

    static public function getEditButton($id, $arrAtr = array(), $href = "javascript:void(0);", $img_title = 'Edytuj') {
        if (self::$html == null) {
            self::$html = new Html();
        }
        if (trim($href)) {
            $arrAtr[] = array("href", $href);
        }
        return self::$html->tagElementSimple("a", $id, "", $arrAtr, self::getEditImage($img_title));
    }

    static public function getSetIntervalFunctions() {
        if (Config::get('modules.interval.modules')) {
            $modulesArray = explode(",", Config::get('modules.interval.modules'));
        }else
            return "";
    }

}

?>
